package com.bank.lenovoz5;

import android.content.Context;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.text.TextUtils;
import android.util.Log;

import com.entity.SMSCode;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.LogToFile;

import java.text.DecimalFormat;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.PAUSE;
import static com.utils.ChatClient.RUNING;
import static com.utils.ChatClient.S_paused_C;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.requestSMSCode;
import static com.utils.ChatClient.setDevicesLog;
import static com.utils.ChatClient.user;
import static com.utils.Constants.orderBankName;

/**
 * 桂林银行股份有限公司自动化脚本
 * 修改时间：2019年9月16日13:50:45
 */
public class Z5GUILINBank {
    private UiDevice mDevice;

    private static String sumMoney = "-1";
    private static String BANK_NAME = "桂林银行";
    private static String BANK_FLAG = "GUILIN";

    // true为测试，false为正式
    private final static boolean IS_TEST = false;

    //金额键盘 顺序为1234567890.
    private static int[][] xy_123m = new int[][]{
            {300, 1460}, {540, 1460}, {780, 1460},
            {300, 1630}, {540, 1630}, {780, 1630},
            {300, 1780}, {540, 1780}, {780, 1780},
            {540, 1945}, {780, 1945}};

    //卡号键盘 顺序为1234567890 Z5
    private static int[][] xy_Card_Number = new int[][]{
            {300, 1520}, {540, 1520}, {780, 1520},
            {300, 1670}, {540, 1670}, {780, 1670},
            {300, 1835}, {540, 1835}, {780, 1835},
            {540, 2015}};

    // 字母键盘
    private static int[][] xy_abc = new int[][]{
            {84, 1440}, {186, 1440}, {293, 1440}, {389, 1440}, {493, 1440}, {606, 1440}, {715, 1440}, {818, 1440}, {918, 1440},
            {1017, 1440},
            {122, 1630}, {222, 1630}, {330, 1630}, {433, 1630}, {557, 1630}, {655, 1630}, {773, 1630}, {863, 1630}, {970, 1630},
            {222, 1790}, {334, 1790}, {442, 1790}, {544, 1790}, {654, 1790}, {754, 1790}, {860, 1790}};

    // 联想s5 特殊字符 黑色 顺序为1234567890
    private static int[][] xy_zf = new int[][]{
            {50, 1450}, {150, 1450}, {270, 1450},
            {370, 1450}, {470, 1450}, {580, 1450},
            {680, 1450}, {790, 1450}, {920, 1450},
            {1010, 1450}};
    private int smsFlag = 1;
    // true为字符，false为数字
    private boolean boo = true;

    public Z5GUILINBank(Context context, UiDevice mDevice) throws UiObjectNotFoundException {
        this.mDevice = mDevice;
        Constants.getScreenHeight(context, BANK_NAME);
        // 获取账户信息
        if (!IS_TEST) {
            Constants.getAccountInformation(Constants.getMethod(0));
        }
        Constants.tryingToReadAccountInformation(mDevice, BANK_NAME);
        // 触发登录页面
        triggerLandingPage(Constants.getMethod(0));
        // 登录页面
        Login();
    }

    /**
     * 触发登录页面
     *
     * @param method 栈的信息
     * @throws UiObjectNotFoundException UI异常
     */
    private void triggerLandingPage(String method) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                showLog("首页点击转账汇款失败");
                ChatClient.timer(method, ChatClient.errorStr);
                return;
            }
            UiObject zhuanzhang1 = mDevice.findObject(new UiSelector().text("转账汇款").resourceId("com.guilinbank" +
                    ".mobilebank:id/tv_gv_item_Name"));
            if (zhuanzhang1.exists()) {
                //进入转账
                LogToFile.d("========", "点击转账汇款1");
                zhuanzhang1.click();
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                LogToFile.d("========", "无不再提示对话框");
                return;
            }
            UiObject noLongerPrompt = mDevice.findObject(new UiSelector().text("不再提示").className("android.widget.TextView"));
            UiObject noLongerPrompt1 = mDevice.findObject(new UiSelector().descriptionContains("不再提示").className("android" +
                    ".widget.TextView"));
            if (noLongerPrompt.exists()) {
                //进入转账
                LogToFile.d("========", "不再提示");
                noLongerPrompt.click();
                break;
            } else if (noLongerPrompt1.exists()) {
                //进入转账
                LogToFile.d("========", "不再提示");
                noLongerPrompt1.click();
                break;
            }
        }
    }

    //进入登录页面补充用户信息
    private void Login() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
                LogToFile.d("========", "未找到密码输入框");
                break;
            }
            UiObject et = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入登录密码"));
            if (et.exists()) {
                et.click();
                sleep(ChatClient.overtime_3);
                // 输入手机号登陆密码
                if (IS_TEST) {
                    String pad = "aa369369";
                    setClick_new(pad);
                } else {
                    setClick_new(user.getPwd());
                }
                break;
            }
        }
        sleep(ChatClient.overtime_1);
        mDevice.click(550, 250);
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                LogToFile.d("========", "未找到登陆按钮");
                break;
            }
            UiObject loginBu1 = mDevice.findObject(new UiSelector().className("android.widget.Button").text("登录"));
            if (loginBu1.exists()) {
                loginBu1.click();
                break;
            }
        }
        safetyCertificate();
        sleep(ChatClient.overtime_2);
        //转账金额
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_20) {
                showLog("登录验证失败");
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.TextView"));
            if (webView.exists()) {
                //登录成功
                ChatClient.loginS();
                sleep(ChatClient.overtime_5);
                break;
            }
        }
        setRemittance();
    }

    private void clickNumKey(String bankNo) {
        char[] array = bankNo.toCharArray();
        for (char c : array) {
            int i = Integer.parseInt(String.valueOf(c));
            mDevice.click(xy_zf[i][0], xy_zf[i][1]);
            showLog("0--6点短信验证码输入点击---" + i);
            sleep(1000);
        }
    }

    private void safetyCertificate() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        sleep(ChatClient.overtime_3);
        showLog("点击获取按钮");
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showLog("未检测到安全认证");
                return;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("获取").className("android.widget.Button"));
            if (button.exists()) {
                showLog("获取");
                button.click();
                break;
            }
        }
        if (user.getUseType().equals("1")) {
            sleep(ChatClient.overtime_5);
            ChatClient.begintime = System.currentTimeMillis();
            while (true) {
                long nowTime1 = System.currentTimeMillis();
                if (nowTime1 - ChatClient.begintime > ChatClient.overtime_90) {
                    ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
                    break;
                }
                if (TextUtils.isEmpty(Constants.CODE)) {
                    sleep(ChatClient.overtime_3);
                } else {
                    showLog("返回短信验证码为：" + Constants.CODE);
                    break;
                }
            }
            while (true) {
                UiObject kl = mDevice.findObject(new UiSelector().text("请输入短信验证码").className("android.widget.EditText"));
                UiObject k2 = mDevice.findObject(new UiSelector().text("输入短信验证码").className("android.widget.EditText"));
                if (kl.exists()) {
                    kl.setText(Constants.CODE);
                    break;
                } else if (k2.exists()) {
                    showLog("点击输入短信验证码");
                    k2.click();
                    clickNumKey(Constants.CODE);
                    sleep(ChatClient.overtime_2);
                    mDevice.click(994, 1338);
                    break;
                }
            }
        } else {
            showLog("处理转账短信---无SIM卡");
            setNotSIM_SMS();
        }
        Constants.CODE = "";
        showLog("点击检验短信");
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showLog("未检测到安全认证");
                break;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("检验短信").className("android.widget.Button"));
            if (button.exists()) {
                showLog("点击检验短信");
                button.click();
                break;
            }
        }
    }

    /**
     * 登录成功后进入转账
     */
    private void setRemittance() {
        showLog("进入等待setRemittance()");
        try {
            sleep(ChatClient.overtime_2);
            ChatClient.begintime = System.currentTimeMillis();//开始时间
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                    showLog("进入转账汇款页失败");
                    ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                    return;
                }
                UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
                if (webView.exists()) {
                    webView.click();
                    sleep(ChatClient.overtime_3);
                    break;
                }
            }
            while (true) {
                showLog("while (true)");
                RUNING = list.size() > 0;
                if (RUNING) {
                    orderBankName = Constants.getBank(list.get(0).getBankName(), BANK_NAME);
                    if (ConfirmOrder) {
                        // 查账
                        showLog("进入查账");
                        auditOrder();
                    } else {
                        // 转账
                        showLog("进入转账");
                        remittanceLogin();
                    }
                } else {
                    if (PAUSE) {
                        showLog("remittance");
                        remittance();
                        ChatClient.request();
                    } else {
                        showLog("S_paused_C");
                        S_paused_C();
                        sleep(ChatClient.overtime_3);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            setDevicesLog(e.getMessage());
        }
    }

    /**
     * 获取余额
     *
     * @param isSave 除查账外其他时间查账都要保存为保证余额的实时性 true:保存到本地 false：不保存
     * @throws UiObjectNotFoundException 捕获控件异常
     */
    private void getTheBalance(boolean isSave) throws UiObjectNotFoundException {
        showLog("获取余额");
        while (true) {
            UiObject cardView = mDevice.findObject(new UiSelector().className("android.widget.ScrollView").index(2));
            UiObject transferView = cardView.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
            UiObject transferView1 = transferView.getChild(new UiSelector().className("android.widget.TextView").index(0));
            if (transferView1.exists()) {
                Log.d("instance(3)", "=instance(3)==========transferView1.getText()");
                if (!StringUtils.isEmpty(transferView1.getText()) && transferView1.getText().contains("可用余额")) {
                    Log.d("====---transferView1.getText()-====", transferView1.getText());
                    sumMoney = transferView1.getText().substring(transferView1.getText().indexOf("：") + 1,
                            transferView1.getText().length() - 1);
                } else {
                    Log.d("instance(3)", "=instance(3)==========transferView1.getContentDescription()");
                    if (transferView1.getContentDescription().contains("可用余额")) {
                        Log.d("====---transferView1.getText()-====", transferView1.getContentDescription());
                        sumMoney = transferView1.getContentDescription().substring(transferView1.getContentDescription()
                                .indexOf("：") + 1, transferView1.getContentDescription().length() - 1);
                    }
                }
            }
            sumMoney = sumMoney.replaceAll(",", "");
            Log.d("====---money-====", "====money===:" + sumMoney);
            if (!sumMoney.equals("")) {
                if (isSave) {
                    showLog("本地保存余额");
                    String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                    FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                }
                C_updateBalance_W(Double.parseDouble(sumMoney));
                sleep(ChatClient.overtime_1);
            }
            break;
        }
    }

    /**
     * 转账汇款
     */
    private void remittanceLogin() throws UiObjectNotFoundException {
        getTheBalance(true);
        addWorkTime(ChatClient.overtime_60);
        //收款人
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject skr = mDevice.findObject(new UiSelector().text("请输入姓名").className("android.widget.EditText"));
            if (skr.exists()) {
                skr.setText(list.get(0).getUserName());
                break;
            }
        }

        //账号
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject skzh = mDevice.findObject(new UiSelector().text("请输入收款人账号").className("android.widget.EditText"));
            if (skzh.exists()) {
                skzh.click();
                sleep(1000);
                showLog("点击切换数字");
                mDevice.click(75, 1930);
                sleep(1000);
                setClickCardNumber(list.get(0).getBankNo());
                sleep(1000);
                showLog("点击关闭键盘");
                mDevice.click(994, 1338);
                showLog("银行卡号输入完成");
                break;
            }
        }
        // 所属银行
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject bankName = mDevice.findObject(new UiSelector().text("选择开户行").className("android.widget.Button"));
            if (bankName.exists()) {
                bankName.click();
                showLog("自动输入银行名称完成");
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        showLog("检测是否自动适配了开户行");
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("自动适配成功");
                break;
            }
            UiObject textView = mDevice.findObject(new UiSelector().text("请输入关键字").className("android.widget.EditText"));
            if (textView.exists()) {
                textView.setText(orderBankName);
                sleep(ChatClient.overtime_2);
                UiObject button1 = mDevice.findObject(new UiSelector().text("查询").className("android.widget.Button"));
                showLog("重复交易提醒-----点击是");
                button1.click();
                sleep(ChatClient.overtime_5);
                UiObject textView1 = mDevice.findObject(new UiSelector().text(orderBankName).className("android.widget.TextView"));
                if (textView1.exists()) {
                    mDevice.click(550, 310);
                    break;
                } else {
                    failureToReport("银行名称错误", 1, 0);
                    back();
                    sleep(ChatClient.overtime_2);
                    while (true) {
                        UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
                        if (webView.exists()) {
                            webView.click();
                            break;
                        }
                    }
                    return;
                }
            }
        }
        sleep(ChatClient.overtime_3);
        EnterTheAmount();
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("未找到下一步");
                break;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("下一步").className("android.widget.Button"));
            if (button.exists()) {
                showLog("下一步");
                button.click();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        showLog("检测重复交易提醒");
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("未检测到重复交易提醒");
                break;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("重复交易提醒").className("android.widget.TextView"));
            if (button.exists()) {
                UiObject button1 = mDevice.findObject(new UiSelector().text("是").className("android.widget.Button"));
                showLog("重复交易提醒-----点击是");
                button1.click();
                break;
            }
        }
        /*
         * 处理短信与转账密码
         */
        smsFlag = 1;
        SMSOrPwd();
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject state = mDevice.findObject(new UiSelector().index(0).className("android.widget.TextView").text("交易结果"));
            if (state.exists()) {
                LogToFile.d("====结果页====", "====跳转到结果页====");
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
                sleep(ChatClient.overtime_3);
                getUserInfo();
                break;
            } else if (state.exists()) {
                if (state.getText().contains("您的汇款正在处理中")) {
                    LogToFile.d("====等待跳转到结果页====", "====等待跳转到结果页====");
                }
            }
        }
    }

    private void EnterTheAmount() throws UiObjectNotFoundException {
        //转账金额
        UiObject transferAmount = mDevice.findObject(new UiSelector().text("请输入转账金额").className("android.widget.EditText"));
        if (transferAmount.exists()) {
            transferAmount.click();
        }
        sleep(ChatClient.overtime_2);
        //设置金额
        setClickM(list.get(0).getMoney());
        sleep(ChatClient.overtime_2);
        showLog("点击关闭键盘");
        mDevice.click(994, 1338);
        sleep(ChatClient.overtime_2);
        AmountOfContrast();
    }

    private void AmountOfContrast() throws UiObjectNotFoundException {
        showLog("订单金额与输入金额对比");
        while (true) {
            UiObject transferAmount = mDevice.findObject(new UiSelector().className("android.widget.ScrollView").index(3));
            if (transferAmount.exists()) {
                UiObject transferAmountFromParent1 = transferAmount.getFromParent(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject linearLayoutFromParent = transferAmountFromParent1.getChild(new UiSelector().className("android.widget.ScrollView").index(0));
                UiObject transferAmountFromParent = linearLayoutFromParent.getFromParent(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject linearLayoutFromParent0 = transferAmountFromParent.getChild(new UiSelector().className("android.widget.HorizontalScrollView").index(1));
                UiObject linearLayoutFromParent1 = linearLayoutFromParent0.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject linearLayoutFromParent2 = linearLayoutFromParent1.getChild(new UiSelector().className("android.widget.LinearLayout").index(1));
                UiObject transferAmountEditText = linearLayoutFromParent2.getChild(new UiSelector().className("android.widget.EditText").index(0));
                if (transferAmountEditText.exists()) {
                    if (transferAmountEditText.getText().contains("请输入转账金额")) {
                        EnterTheAmount();
                    } else {
                        if (Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(transferAmountEditText.getText())) {
                            showLog("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + transferAmountEditText.getText() + "--->金额相等");
                        } else {
                            int length = transferAmountEditText.getText().length() + 1;
                            showLog("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + transferAmountEditText.getText() + "--->金额不相等");
                            sleep(1000);
                            transferAmountEditText.click();
                            sleep(2000);
                            for (int i = 0; i < length; i++) {
                                mDevice.click(990, 1520);
                                sleep(500);
                            }
                            sleep(2000);
                            setClickM(list.get(0).getMoney());
                            sleep(ChatClient.overtime_2);
                            showLog("点击关闭键盘");
                            mDevice.click(994, 1338);
                            sleep(ChatClient.overtime_2);
                            AmountOfContrast();
                        }
                    }
                    break;
                }
            }
        }
    }

    /**
     * 转账错误处理
     */
    private void errorSMSValidation() throws UiObjectNotFoundException {
        showLog("获取错误信息");
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_8) {
                showLog("未检测到错误提示");
                break;
            }
            String errorMsg = errorMsg();
            if (!StringUtils.isEmpty(errorMsg)) {
                if (errorMsg.contains("错误")) {
                    if (smsFlag < 3) {
                        smsFlag++;
                        mDevice.pressBack();
                        SMSOrPwd();
                        break;
                    } else {
                        ChatClient.timer(Constants.getMethod(0), "短息获取超过三次");
                        return;
                    }
                }
            }
        }
    }

    private String errorMsg() throws UiObjectNotFoundException {
        UiObject errorMsgTitle = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("错误提示"));
        String errorResult;
        if (errorMsgTitle.exists()) {
            errorResult = errorMsgTitle.getText();
            showLog("errorMsg  = " + errorResult);
            return errorResult;
        }
        return "";
    }

    /**
     * 短信与转账密码处理
     */
    private void SMSOrPwd() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        sleep(ChatClient.overtime_3);
        setPhoneSMS();
        sleep(ChatClient.overtime_5);
        errorSMSValidation();
    }

    /**
     * 处理无SIM卡手机短信逻辑
     */
    private void setNotSIM_SMS() throws UiObjectNotFoundException {
        if (smsFlag > 3) {
            ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
            return;
        }
        sleep(ChatClient.overtime_10);
        SMSCode smsCode = requestSMSCode(user.getUserName(), user.getBankId());
        if (StringUtils.isEmpty(smsCode.getSmscode())) {
            showLog("短信验证码为空，点击获取按钮");
            while (true) {
                UiObject button = mDevice.findObject(new UiSelector().text("获取").className("android.widget.Button").index(2));
                if (button.exists()) {
                    showLog("获取");
                    button.click();
                    sleep(ChatClient.overtime_2);
                    smsFlag++;
                    setNotSIM_SMS();
                    break;
                }
            }
        } else {
            showLog("返回短信验证码为：" + smsCode.getSmscode());
            while (true) {
                UiObject kl = mDevice.findObject(new UiSelector().text("请输入短信验证码").className("android.widget.EditText"));
                UiObject k2 = mDevice.findObject(new UiSelector().text("输入短信验证码").className("android.widget.EditText"));
                if (kl.exists()) {
                    kl.setText(smsCode.getSmscode() + "");
                    break;
                } else if (k2.exists()) {
                    k2.setText(smsCode.getSmscode() + "");
                    break;
                } else {
                    sleep(ChatClient.overtime_2);
                    // 点击短信输入框
                    mDevice.click(500, 1230);
                    sleep(ChatClient.overtime_2);
                    //点击删除短信验证码
                    mDevice.click(766, 1244);
                    sleep(ChatClient.overtime_2);
                    // 点击关闭键盘
                    mDevice.click(990, 1338);
                    sleep(ChatClient.overtime_5);
                }
            }
        }
    }

    /**
     * 监听短信点击输入验证码
     */
    private void setPhoneSMS() throws UiObjectNotFoundException {
        showLog("点击获取按钮");
        while (true) {
            UiObject button = mDevice.findObject(new UiSelector().text("获取").className("android.widget.Button").index(2));
            if (button.exists()) {
                showLog("获取");
                button.click();
                break;
            }
        }
        if (user.getUseType().equals("1")) {
            sleep(ChatClient.overtime_5);
            ChatClient.begintime = System.currentTimeMillis();
            while (true) {
                long nowTime1 = System.currentTimeMillis();
                if (nowTime1 - ChatClient.begintime > ChatClient.overtime_90) {
                    ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
                    break;
                }
                if (TextUtils.isEmpty(Constants.CODE)) {
                    sleep(ChatClient.overtime_3);
                } else {
                    showLog("返回短信验证码为：" + Constants.CODE);
                    break;
                }
            }
            while (true) {
                UiObject kl = mDevice.findObject(new UiSelector().text("请输入短信验证码").className("android.widget.EditText"));
                if (kl.exists()) {
                    kl.setText(Constants.CODE);
                    break;
                } else if (smsFlag > 1) {
                    sleep(ChatClient.overtime_2);
                    // 点击短信输入框
                    mDevice.click(500, 1230);
                    sleep(ChatClient.overtime_2);
                    //点击删除短信验证码
                    mDevice.click(766, 1244);
                    sleep(ChatClient.overtime_2);
                    // 点击关闭键盘
                    mDevice.click(990, 1338);
                    sleep(ChatClient.overtime_5);
                }
            }
        } else {
            showLog("处理转账短信---无SIM卡");
            setNotSIM_SMS();
        }
        Constants.CODE = "";
        sleep(ChatClient.overtime_3);
        //取款密码输入
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > 3000) {
                break;
            }
            UiObject bpwd = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入6位交易密码"));
            if (bpwd.exists()) {
                bpwd.click();
                sleep(ChatClient.overtime_2);
                LogToFile.d("---截取取款密码的键盘---", "-----截取取款密码的键盘-----");
                // 收起键盘
                setClickCardNumber(user.getBankpwd());
                sleep(ChatClient.overtime_2);
                LogToFile.d("", "======================--------->");
                mDevice.click(536, 135);
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        showLog("获取点击提交");
        while (true) {
            UiObject state = mDevice.findObject(new UiSelector().index(0).className("android.widget.Button").text("提交"));
            if (state.exists()) {
                showLog("点击提交");
                state.click();
                break;
            }
        }
    }

    /**
     * 字母和数字键盘的切换
     *
     * @param checkStr 待校验参数
     * @return true 为数字  false 为字符
     */
    public static boolean isNumeric(String checkStr) {
        try {
            Integer.parseInt(checkStr);
            return true;
        } catch (NumberFormatException err) {
            return false;
        }
    }

    /**
     * 登陆密码
     *
     * @param pad 登陆密码
     */
    private void setClick_new(String pad) {
//        LogToFile.d("====输入手机APK登陆密码====", "===输入手机APK登陆密码===" + pad);
        Exception exception = new Exception();
        StackTraceElement[] trace = exception.getStackTrace();
        String method = trace[0].getMethodName();
        try {
            char[] abc = "qwertyuiopasdfghjklzxcvbnm".toCharArray();//char数组
            char[] zf = "1234567890".toCharArray();//char数组
            char[] pwd = pad.toCharArray();//char数组
            char[] num_abc;//char数组
            sleep(ChatClient.overtime_3);
            for (char c : pwd) {
                if (isNumeric(String.valueOf(c))) {
                    num_abc = zf;
                } else {
                    num_abc = abc;
                }
                for (int i = 0; i < num_abc.length; i++) {
                    if (num_abc[i] == c) {
                        if (isNumeric(String.valueOf(c))) {
                            if (boo) {
                                sleep(500);
                                clickClickOnTheNumbers();
                            }
                            sleep(500);
                            mDevice.click(xy_zf[i][0], xy_zf[i][1]);
                        } else {
                            if (!boo) {
                                sleep(500);
                                clickClickOnTheNumbers();
                            }
                            mDevice.click(xy_abc[i][0], xy_abc[i][1]);
                            sleep(500);
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            showLog("点击特殊字符=======为空");
            ChatClient.timer(method, "");
        }
    }

    /**
     * 点击特殊字符
     */
    private void clickClickOnTheNumbers() {
        mDevice.click(145, 1970);
        boo = !boo;
    }

    /**
     * 境内汇款页面
     */
    private void remittance() throws UiObjectNotFoundException {
        while (true) {
            UiObject skr = mDevice.findObject(new UiSelector().className("android.widget.EditText").index(1).text("请输入姓名"));
            if (skr.exists()) {
                showLog("检测进入已转账页面");
                break;
            }
        }
        getTheBalance(true);
        ChatClient.request();
        if (ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            orderBankName = Constants.getBank(list.get(0).getBankName(), BANK_NAME);
            // 转账
            showLog("进入转账");
            remittanceLogin();
            return;
        }
        sleep(ChatClient.overtime_2);
        while (true) {
            UiObject skr = mDevice.findObject(new UiSelector().className("android.widget.TextView").index(0).text("付款账号"));
            if (skr.exists()) {
                showLog("检测到付款账号");
                mDevice.click(872, 942);
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("检测到卡号弹窗失败");
                return;
            }
            UiObject skr = mDevice.findObject(new UiSelector().resourceId("android:id/text1").index(0));
            if (skr.exists()) {
                showLog("检测到卡号弹窗");
                skr.click();
                break;
            }
        }
    }

    /**
     * 查账
     */
    private void auditOrder() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_3);
        //进入转账页面
        getTheBalance(false);
        sleep(ChatClient.overtime_3);
        mDevice.pressBack();
        sleep(ChatClient.overtime_3);
        showLog("准备点击------>查看历史转账结果");
        while (true) {
            UiObject seeTheHistory = mDevice.findObject(new UiSelector().className("android.widget.Button").index(0).text("查看历史转账结果"));
            if (seeTheHistory.exists()) {
                seeTheHistory.click();
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        showLog("准备点击------>行内转账");
        while (true) {
            UiObject transfer = mDevice.findObject(new UiSelector().className("android.widget.TextView").index(1).text("行内转账"));
            if (transfer.exists()) {
                transfer.click();
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        showLog("准备点击------>跨行转账");
        while (true) {
            UiObject remittance = mDevice.findObject(new UiSelector().resourceId("android:id/text1").index(2).text("跨行转账"));
            if (remittance.exists()) {
                remittance.click();
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        showLog("准备点击------>查询");
        while (true) {
            UiObject query = mDevice.findObject(new UiSelector().className("android.widget.Button").index(0).text("查询"));
            if (query.exists()) {
                query.click();
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowTime = System.currentTimeMillis();
            if ((nowTime - ChatClient.begintime) > ChatClient.overtime_10) {
                showLog("没有记录");
                newAuditProcess();
                LogToFile.d("====转账详情页====", "====返回主页====");
                mDevice.pressBack();
                sleep(ChatClient.overtime_2);
                mDevice.pressBack();
                sleep(ChatClient.overtime_2);
                return;
            }
            UiObject listView = mDevice.findObject(new UiSelector().className("android.widget.TextView").index(0).text("收款人"));
            if (listView.exists()) {
                showLog("有转账记录");
                mDevice.click(500, 300);
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        String money = "0";
        String userName = "";
        String bankNo;
        String results = "";
        //获取交易记录
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            sleep(ChatClient.overtime_2);
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
//                failureToReport("有记录交易查询超时", 1);
                newAuditProcess();
                back();
                sleep(ChatClient.overtime_2);
                sleep(ChatClient.overtime_2);
                while (true) {
                    UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
                    if (webView.exists()) {
                        webView.click();
                        break;
                    }
                }
                return;
            }

            UiObject scrollViewUserName = mDevice.findObject(new UiSelector().className("android.widget.HorizontalScrollView").index(5));
            if (scrollViewUserName.exists()) {
                UiObject linearLayoutUserName = scrollViewUserName.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject textViewMoney = linearLayoutUserName.getChild(new UiSelector().className("android.widget.TextView").index(1));
                money = textViewMoney.getText().substring(0, textViewMoney.getText().length() - 1);
                showLog("====textViewMoney===" + money);
            }
            UiObject scrollViewUserName2 = mDevice.findObject(new UiSelector().className("android.widget.HorizontalScrollView").index(7));
            if (scrollViewUserName2.exists()) {
                UiObject linearLayoutUserName = scrollViewUserName2.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject textView = linearLayoutUserName.getChild(new UiSelector().className("android.widget.TextView").index(1));
                results = textView.getText();
//                showLog("====results===" + results);
            }
            UiObject scrollViewUserName1 = mDevice.findObject(new UiSelector().className("android.widget.HorizontalScrollView").index(2));
            if (scrollViewUserName1.exists()) {
                UiObject linearLayoutUserName = scrollViewUserName1.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject textView = linearLayoutUserName.getChild(new UiSelector().className("android.widget.TextView").index(1));
                userName = textView.getText();
//                showLog("====textViewUserName===" + userName);
            }
            UiObject scrollViewUserName3 = mDevice.findObject(new UiSelector().className("android.widget.HorizontalScrollView").index(3));
            if (scrollViewUserName1.exists()) {
                UiObject linearLayoutBankNo = scrollViewUserName3.getChild(new UiSelector().className("android.widget.LinearLayout").index(0));
                UiObject textView = linearLayoutBankNo.getChild(new UiSelector().className("android.widget.TextView").index(1));
                bankNo = textView.getText().substring(textView.getText().length() - 4);
//                showLog("====scrollViewUserName3===" + bankNo);
                break;
            }
        }
        String money1 = money.replaceAll(",", "");
        System.out.println(Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(money1));

        if (Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(money1) && userName.contains(list.get(0)
                .getUserName()) && list.get(0).getBankNo().contains(bankNo)) {
            failureToReport(results, Constants.getStr(results), 1);
        } else {
            newAuditProcess();
        }
        back();
        sleep(ChatClient.overtime_2);
        while (true) {
            UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
            if (webView.exists()) {
                webView.click();
                break;
            }
        }
    }

    /**
     * 查账时走金额变化判断  使用地方为：1、未找到和上一笔订单相同的金额和名称的订单 2、查账时出现异常超时 3、没有记录时
     */
    private void newAuditProcess() {
        showLog("未查到相同订单");
        String sumMoneyFile = user.getUserName() + BANK_NAME + "_sumMoney.txt";
        String oldMoney = FileHelper.readSDFile(sumMoneyFile);
        switch (Constants.changeInAmount(BANK_NAME, oldMoney, sumMoney, list.get(0).getMoney())) {
            case "0":
                failureToReport("交易成功", 0, 1);
                break;
            case "1":
                failureToReport("交易待处理...", 1, 1);
                break;
            case "4":
                failureToReport("未查到条目", 4, 1);
                break;
        }
    }

    private void failureToReport(String info, int state, int auditAndTransfer) {
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'" + BANK_NAME +
                "'," + "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':" + state + "," +
                "'type':1";
        showLog("mobileD = " + mobileD);
        showLog("json = " + json);
        String requestName;
        if (auditAndTransfer == 0) {
            requestName = ChatClient.M_SEND_TRADE_RESULT_P;
        } else {
            requestName = ChatClient.S_CONFIRM_TRADE_RESULT_C;
        }
        ChatClient.msg("<YZF>{'header':'" + requestName + "'," + json + "," + mobileD + "}</YZF>");
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
        sleep(ChatClient.overtime_2);
    }

    /**
     * 完成转账后回复服务端
     */
    private void getUserInfo() throws UiObjectNotFoundException {
        Exception exception = new Exception();
        StackTraceElement[] trace = exception.getStackTrace();
        String method = trace[0].getMethodName();
        String type = "";
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(method, ChatClient.errorStr);
                break;
            }
            //  获取交易结果 桂林银行股份有限公司无交易完成，交易中。。。。只有交易已提交到对方账户  梁钊
            UiObject state1 = mDevice.findObject(new UiSelector().text("继续转账").className("android.widget.Button"));
            if (state1.exists()) {
                UiObject textView = mDevice.findObject(new UiSelector().className("android.widget.TextView").index(1));
                if (textView.exists()) {
                    type = textView.getText();
                    if (type.equals("")) {
                        type = textView.getContentDescription();
                    }
                }
                break;
            }
        }
        LogToFile.d("=====确定收款银行====", "=====转账完成====" + type);
        if (Constants.getStr(type) == 0) {
            DecimalFormat formater = new DecimalFormat("#0.##");
            sumMoney = formater.format(Double.parseDouble(sumMoney) - Double.parseDouble(list.get(0).getMoney()));
            showLog("本地保存余额");
            String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
        }
        type = type.replaceAll("\r|\n|\\s", "");
        failureToReport(type, Constants.getStr(type), 0);
        sleep(ChatClient.overtime_2);
        //返回
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(method, ChatClient.errorStr);
                break;
            }
            UiObject state1 = mDevice.findObject(new UiSelector().text("继续转账").className("android.widget.Button"));
            if (state1.exists()) {
                LogToFile.d("====结果页====", "====点击继续转账====");
                state1.click();
                break;
            }
        }

        Constants.CODE = "";
        while (true) {
            UiObject next1 = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
            UiObject next4 = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.TextView"));
            if (next1.exists() || next4.exists()) {
                LogToFile.d("====转账汇款页====", "====进入转账汇款页====");
                break;
            }
        }
        showLog("获取转账汇款按钮");
        while (true) {
            UiObject webView = mDevice.findObject(new UiSelector().text("转账汇款").className("android.widget.Button"));
            if (webView.exists()) {
                webView.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }
    }

    /**
     * 模拟点击金额
     */
    private void setClickM(String money_) {
        try {
            char[] num = "1234567890.".toCharArray();//char数组
            char[] money = money_.toCharArray();//char数组

            for (char c : money) {
                for (int i = 0; i < num.length; i++) {
                    if (num[i] == c) {
                        mDevice.click(xy_123m[i][0], xy_123m[i][1]);
                        sleep(1000);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 模拟输入账户与密码共用
     */
    private void setClickCardNumber(String money_) {
        try {
            char[] num = "1234567890".toCharArray();//char数组
            char[] money = money_.toCharArray();//char数组

            for (char c : money) {
                for (int i = 0; i < num.length; i++) {
                    if (num[i] == c) {
                        mDevice.click(xy_Card_Number[i][0], xy_Card_Number[i][1]);
                        sleep(500);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回
     */
    private void back() {
        LogToFile.d("====转账详情页====", "====返回主页====");
        mDevice.pressBack();
        sleep(ChatClient.overtime_2);
        mDevice.pressBack();
        sleep(ChatClient.overtime_2);
        mDevice.pressBack();
    }

    private void showLog(String msg) {
        LogToFile.showLog(BANK_NAME, msg);
    }
}
